package cn.growthgate.fgo.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import cn.growthgate.fgo.common.base.BaseServiceImpl;
import cn.growthgate.fgo.entity.ServantTraits;
import cn.growthgate.fgo.entity.enums.ServantTrait;
import cn.growthgate.fgo.mapper.ServantTraitsMapper;
import cn.growthgate.fgo.service.IServantTraitsService;

/**
 * <p>
 * 从者特性 服务实现类
 * </p>
 *
 * @author GrowthGate
 * @since 2019-06-17
 */
@Service
public class ServantTraitsServiceImpl extends BaseServiceImpl<ServantTraitsMapper, ServantTraits>
		implements IServantTraitsService {

	@Override
	public List<ServantTraits> selectByServantId(Long servantId) {
		return selectList(newWrapper().eq("servantId", servantId));
	}

	@Override
	public boolean saveTraits(Long servantId, ServantTrait[] traits) {
		List<ServantTrait> trainList = new ArrayList<ServantTrait>(Arrays.asList(traits));
		// 旧特性
		List<ServantTraits> oTrait = selectByServantId(servantId);
		// 需要删除的特性id
		List<Long> dTraitIds = new ArrayList<>();
		for (ServantTraits servantTraits : oTrait) {
			ServantTrait trait = servantTraits.getTrait();
			if (trainList.contains(trait)) {
				trainList.remove(trait);
			} else {
				dTraitIds.add(servantTraits.getId());
			}
		}
		// 新特性
		List<ServantTraits> nTrait = trainList.stream().map(train -> {
			ServantTraits servantTraits = new ServantTraits();
			servantTraits.setServantId(servantId);
			servantTraits.setTrait(train);
			return servantTraits;
		}).collect(Collectors.toList());
		boolean insertSuccess = insertBatch(nTrait);
		boolean deleteSuccess = deleteBatchIds(dTraitIds);
		return insertSuccess && deleteSuccess;
	}

}
